package com.hoshiicloud.goods.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.constant.DeleteStatusEnum;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.goods.dto.sku.SkuDTO;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.spu.ExtSpu;
import com.hoshiicloud.goods.feign.StoreFeignService;
import com.hoshiicloud.goods.param.sku.LockSkuStockParam;
import com.hoshiicloud.goods.param.sku.ProductManageQueryParam;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.service.ExtSpuService;
import com.hoshiicloud.goods.service.ProductManageService;
import com.hoshiicloud.goods.service.SkuService;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hoshiicloud.user.entity.store.PlatStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * sku聚合service
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-05-05
 */
@Slf4j
@Service
public class SkuServiceImpl implements SkuService {


    @Autowired
    private ExtSkuService extSkuService;
    @Autowired
    private ProductManageService productManageService;
    @Autowired
    private ExtSpuService extSpuService;

    // 店铺微服务
    @Autowired
    private StoreFeignService storeFeignService;

    @Override
    public Map<Long, SkuDTO> querySKuStockByIds(List<Long> ids) {

        if (org.apache.commons.collections.CollectionUtils.isEmpty(ids)) {
            log.error("查询商品库存失败");
            throw new ServiceException("查询商品库存失败");
        }

        try {
            QueryWrapper<ExtSku> queryWrapper = new QueryWrapper<>();
            queryWrapper.in(true, "esku.id", ids);
            // queryWrapper.lambda().in(true, ExtSku::getSkuId, ids);
            List<SkuDTO> skuDTOList = extSkuService.listSKuStockByIds(queryWrapper);
            Map<Long, SkuDTO> skuVOS = new HashMap<>(16);
            for (SkuDTO skuDTO : skuDTOList) {
                skuVOS.put(skuDTO.getExtSkuId(), skuDTO);
            }
//            ids.sort(null);//排序
//            List<ExtSku> extSkuList = extSkuService.getByIds(ids, StringUtils.join(ids, ""));
//            if (CollectionUtils.isNotEmpty(extSkuList)) {
//                Map<Long, SkuDTO> skuVOS = new HashMap<>();
//                SkuDTO skuVO = null;
//                Long companyid = null;
//                Long platformid = null;
//                Long baseskuid = null;
//                ExtSpu extSpu = null;
//                QueryWrapper<ProductManage> queryWrapper = null;
//                IPage<ProductManage> page = new Page<>(0, 1);
//                for (ExtSku extSku : extSkuList) {
//                    platformid = extSku.getPlatformid();
//                    companyid = extSku.getCompanyid();
//                    baseskuid = extSku.getSkuid();
//                    //获取扩展spu
//                    extSpu = extSpuService.getById(extSku.getSpuid());
//                    BaseSpu baseSpu = baseSpuService.getById(extSpu.getSpuid());
//                    queryWrapper = new QueryWrapper();
//                    queryWrapper.eq(true, "companyid", companyid);
//                    queryWrapper.eq(true, "platformid", platformid);
//                    queryWrapper.eq(true, "skuid", baseskuid);
//                    queryWrapper.eq(true, "deleted", 0);
//                    IPage<ProductManage> pageList = productManageService.page(page, queryWrapper);
//                    if (pageList != null) {
//                        List<ProductManage> productManageList = pageList.getRecords();
//                        if (CollectionUtils.isNotEmpty(productManageList)) {
//                            ProductManage pm = productManageList.get(0);
//                            skuVO = new SkuDTO();
//                            skuVO.setCompanyid(companyid);
//                            skuVO.setSkuid(extSku.getSkuid());
//                            skuVO.setStoreEnough(extSku.getStoreEnough());
//                            skuVO.setQuantity(pm.getQuantity());
//                            skuVO.setFreezes(pm.getFreezes());
//                            skuVO.setSkuTitle(extSku.getSkuTitle());
//                            skuVO.setSpuNo(baseSpu.getSpuno());
//                            if (extSpu != null) {
//                                skuVO.setSpuTitle(extSpu.getTitle());
//                            }
//                        }
//                        skuVOS.put(extSku.getId(), skuVO);
//                    }
//                }
            return skuVOS;
//            } else {
//                throw new ServiceException(CommonError.error("查询商品SKU库存失败"));
//            }
        } catch (Exception e) {
            throw new ServiceException(CommonError.error("查询商品SKU库存异常"));
        }
    }

    public static void main(String[] args) {

    }

    @Override
    public boolean lockSkuStock(List<LockSkuStockParam> lockSkuStocks) {

        if (org.apache.commons.collections.CollectionUtils.isEmpty(lockSkuStocks)) {
            throw new ServiceException("冻结库存失败");
        }

        try {
            for (LockSkuStockParam lockSkuStock : lockSkuStocks) {
                List<ProductManage> list;
                // 判断如果分销店铺，冻结总店库存
                Response<PlatStore> storeResponse = storeFeignService.queryById(lockSkuStock.getStoreid());
                if (storeResponse.getData().getIsDistributor().equals(1)) {
                    QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(true, ProductManage::getCompanyId, lockSkuStock.getCompanyid())
                            .eq(true, ProductManage::getPlatformId, lockSkuStock.getPlatformid())
                            .eq(true, ProductManage::getBaseSkuId, lockSkuStock.getBaseSkuid())
                            .eq(true, ProductManage::getStoreId, storeResponse.getData().getParentId())
                            .eq(true, ProductManage::getDeleted, DeleteStatusEnum.UN_DELETED.getCode());
                     list = productManageService.list(queryWrapper);
                } else {
                    QueryWrapper<ProductManage> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(true, ProductManage::getCompanyId, lockSkuStock.getCompanyid())
                            .eq(true, ProductManage::getPlatformId, lockSkuStock.getPlatformid())
                            .eq(true, ProductManage::getSkuId, lockSkuStock.getExtSkuid())
                            .eq(true, ProductManage::getStoreId, lockSkuStock.getStoreid())
                            .eq(true, ProductManage::getDeleted, DeleteStatusEnum.UN_DELETED.getCode());
                    list = productManageService.list(queryWrapper);
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    ProductManage pm = list.get(0);
                    pm.setFreezes(pm.getFreezes().add(BigDecimal.valueOf(lockSkuStock.getLockNum())));
                    productManageService.updateById(pm);
                }
            }
            return true;
        } catch (Exception e) {
            throw new ServiceException(CommonError.error("冻结商品库存异常"));
        }
    }

    @Override
    public boolean unLockSkuStock(List<LockSkuStockParam> lockSkuStocks) {

        if (org.apache.commons.collections.CollectionUtils.isEmpty(lockSkuStocks)) {
            throw new ServiceException("解冻库存失败");
        }

        try {
            for (LockSkuStockParam lockSkuStock : lockSkuStocks) {
                List<ProductManage> list;
                // 判断如果分销店铺，冻结总店库存
                Response<PlatStore> storeResponse = storeFeignService.queryById(lockSkuStock.getStoreid());
                if (storeResponse.getData().getIsDistributor().equals(1)) {
                    QueryWrapper<ProductManage> queryWrapper = new QueryWrapper();
                    queryWrapper.eq(true, "company_id", lockSkuStock.getCompanyid());
                    queryWrapper.eq(true, "platform_id", lockSkuStock.getPlatformid());
                    queryWrapper.eq(true, "base_sku_id", lockSkuStock.getBaseSkuid());
                    queryWrapper.eq(true, "store_id", storeResponse.getData().getParentId());
                    queryWrapper.eq(true, "deleted", DeleteStatusEnum.UN_DELETED.getCode());
                    list = productManageService.list(queryWrapper);
                } else {
                    QueryWrapper<ProductManage> queryWrapper = new QueryWrapper();
                    queryWrapper.eq(true, "company_id", lockSkuStock.getCompanyid());
                    queryWrapper.eq(true, "platform_id", lockSkuStock.getPlatformid());
                    queryWrapper.eq(true, "sku_id", lockSkuStock.getExtSkuid());
                    queryWrapper.eq(true, "store_id", lockSkuStock.getStoreid());
                    queryWrapper.eq(true, "deleted", DeleteStatusEnum.UN_DELETED.getCode());
                    list = productManageService.list(queryWrapper);
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    ProductManage pm = list.get(0);
                    pm.setFreezes(pm.getFreezes().subtract(BigDecimal.valueOf(lockSkuStock.getLockNum())));
                    productManageService.updateById(pm);
                }
            }
            return true;
        } catch (Exception e) {
            throw new ServiceException(CommonError.error("解冻商品库存异常"));
        }
    }

    @Override
    public SkuDTO getExtSku(Long id) {

        if (id == null) {
            log.error("根据扩展skuid查询商品信息失败");
            throw new ServiceException("根据扩展skuid查询商品信息失败");
        }

        try {
            ExtSku extSku = extSkuService.getById(id);
            SkuDTO skuDTO = null;
            if (extSku != null) {
                skuDTO = new SkuDTO();
                ExtSpu extSpu = extSpuService.getById(extSku.getSpuId());
                //获取库存及冻结信息
                QueryWrapper<ProductManage> queryWrapper = new QueryWrapper();
                queryWrapper.lambda().eq(ProductManage::getCompanyId, extSku.getCompanyId());
                queryWrapper.lambda().eq(ProductManage::getPlatformId, extSku.getPlatformId());
                queryWrapper.lambda().eq(ProductManage::getSkuId, extSku.getId());
                queryWrapper.lambda().eq(ProductManage::getDeleted, 0);
                List<ProductManage> list = productManageService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(list)) {
                    ProductManage productManage = list.get(0);
                    skuDTO.setQuantity(productManage.getQuantity());
                    skuDTO.setFreezes(productManage.getFreezes());
                }
                skuDTO.setSpuTitle(extSpu.getTitle());
                skuDTO.setCompanyId(extSku.getCompanyId());
                skuDTO.setPlatformId(extSku.getPlatformId());
                skuDTO.setStoreId(extSku.getStoreId());
                skuDTO.setSkuId(extSku.getSkuId());//基础skuid
                skuDTO.setSpuId(extSku.getSpuId());//扩展spuid
                skuDTO.setExtSkuId(extSku.getId());//扩展skuid
                skuDTO.setSkuTitle(extSku.getSkuTitle());
                skuDTO.setGoodsPrice(extSku.getSalePrice());
                skuDTO.setExtendProperty(extSku.getExtendProperty());
                skuDTO.setExtendSpec(extSku.getExtendSpec());
                skuDTO.setStatus(extSku.getStatus());
                skuDTO.setSkuImage(extSku.getSkuImage());
                skuDTO.setStoreEnough(extSku.getStoreEnough());
            }
            return skuDTO;
        } catch (Exception e) {
            log.error("根据扩展skuid查询商品信息异常", e);
            throw new ServiceException("根据扩展skuid查询商品信息异常");
        }
    }

    /**
     * 查询总店库存及Sku信息及库存和冻结数量结果集
     *
     * @param cartVoIdList cartVoIdList
     * @return Map
     */
    @Override
    public Map<Long, SkuDTO> queryHeadOfficeSkuStockByIds(List<Long> cartVoIdList) {

        if (org.apache.commons.collections.CollectionUtils.isEmpty(cartVoIdList)) {
            log.error("查询商品库存失败");
            throw new ServiceException("查询商品库存失败");
        }

        try {
            QueryWrapper<ExtSku> queryWrapper = new QueryWrapper<>();

            queryWrapper.in(true, "t.rec_id", cartVoIdList);

            // 这里查询出了所有的分店库存
            // List<SkuDTO> skuDTOList = extSkuService.listSKuStockByIds(queryWrapper);
            List<SkuDTO> skuDTOList = extSkuService.headOfficeListSKuStockByIds(queryWrapper);

            Map<Long, SkuDTO> skuVOS = new HashMap<>(16);
            for (SkuDTO skuDTO : skuDTOList) {
                skuVOS.put(skuDTO.getExtSkuId(), skuDTO);
            }

            return skuVOS;

        } catch (Exception e) {
            throw new ServiceException(CommonError.error("查询商品SKU库存异常"));
        }
    }
}
